package com.kly.manager.websocket.disruptor;

import com.kly.domain.entity.User;
import com.kly.manager.websocket.model.PictureEditMessageRequest;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;

/**
 * @author admin
 * @date 2025/3/21
 */
@Component
@Slf4j
public class PictureEditEventProducer {

    @Resource
    private Disruptor<PictureEditEvent> pictureEditEventDisruptor;

    public void publishEvent(PictureEditMessageRequest pictureEditMessageRequest, WebSocketSession session, Long pictureId, User user) {
        RingBuffer<PictureEditEvent> ringBuffer = pictureEditEventDisruptor.getRingBuffer();
    //     获取可生产的位置
        long sequence = ringBuffer.next();
        try {
            PictureEditEvent pictureEditEvent = ringBuffer.get(sequence);
            pictureEditEvent.setPictureEditMessageRequest(pictureEditMessageRequest);
            pictureEditEvent.setWebSocketSession(session);
            pictureEditEvent.setPictureId(pictureId);
            pictureEditEvent.setUser(user);
        } finally {
            // 发布事件
            ringBuffer.publish(sequence);
        }
    }

    /**
     * 优雅停机
     */
    @PreDestroy
    public void shutdown() {
        pictureEditEventDisruptor.shutdown();
    }
}
